#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<time.h>
#include<string>
#include"test.hpp"
#include"Task.hpp"


using namespace std;

void* Producer(void* args)
{
    RingQueue::RingQueue<RingQueue::Task<int>>* rq=static_cast<RingQueue::RingQueue<RingQueue::Task<int>>*>(args);
    string opers="+-*/%";
    while(true)
    {
         int x=rand()%100;
         int y=rand()%100;

      char oper[]={'+','-','*','/','%'};
      char op=oper[rand()%opers.size()];

      usleep(10000);
      rq->Push(RingQueue::Task<int>(x,y,op));

      cout<<"Producer生产："<<x<<op<<y<<endl;
      cout<<"============================"<<endl;
    }
    
    pthread_exit((void*)0);
}

void* Consumer(void* args)
{
    RingQueue::RingQueue<RingQueue::Task<int>>* rq=static_cast<RingQueue::RingQueue<RingQueue::Task<int>>*>(args);
    while(true)
    {
       RingQueue::Task<int> task;
        rq->Pop(&task);
        task();

        usleep(10000);

        string ret=task.getResult();

        cout<<"Consumer消费了一个对象，并获得结果"<<ret<<endl;
        cout<<"========================"<<endl;
    }
    pthread_exit((void*)0);
}


int main()
{
    srand((size_t)time(nullptr));

    //创建环形队列
    RingQueue::RingQueue<RingQueue::Task<int>>* rq=new RingQueue::RingQueue<RingQueue::Task<int>>;

    //创建生产者、消费者线程
    pthread_t pro[10],con[10];

    for(int i=0;i<10;i++){
    pthread_create(pro+i,nullptr,Producer,rq);
    }
    for(int i=0;i<10;i++){
    pthread_create(con+i,nullptr,Consumer,rq);
    }

    //等待线程退出
    for(int i=0;i<10;i++){
    pthread_join(pro[i],nullptr);
    }
    for(int i=0;i<10;i++){
    pthread_join(con[i],nullptr);
    }

    delete rq;


    return 0;
}
